// MQTT客户端实现
let mqttClient = null;
let currentConnection = null;

// 初始化MQTT连接
function initMqttConnection(connectionConfig) {
    console.log('初始化MQTT连接，配置:', connectionConfig);
    
    // 保存当前连接
    currentConnection = connectionConfig;
    
    // 创建客户端ID
    const clientId = connectionConfig.clientId || `mqtt_${Math.random().toString(16).substr(2, 8)}`;
    
    // 连接选项
    const options = {
        clientId: clientId,
        username: connectionConfig.username,
        password: connectionConfig.password,
        keepalive: parseInt(connectionConfig.keepalive) || 60,
        clean: true,
        reconnectPeriod: 1000,
        connectTimeout: 30 * 1000
    };
    
    console.log('MQTT连接选项:', options);
    
    try {
        // 创建MQTT客户端
        mqttClient = mqtt.connect(connectionConfig.url, options);
        
        // 连接成功回调
        mqttClient.on('connect', () => {
            console.log('MQTT连接成功');
            // 跳转到数据页面
            window.location.href = 'data.html';
        });
        
        // 连接关闭回调
        mqttClient.on('close', () => {
            console.log('MQTT连接关闭');
        });
        
        // 错误处理回调
        mqttClient.on('error', (err) => {
            console.error('MQTT连接错误:', err);
            alert(`连接失败: ${err.message}`);
        });
        
        // 消息接收回调
        mqttClient.on('message', (topic, message) => {
            console.log(`收到消息 [${topic}]:`, message.toString());
            displayMessage(topic, message.toString());
        });
        
    } catch (err) {
        console.error('MQTT初始化错误:', err);
        alert(`初始化失败: ${err.message}`);
    }
}

// 发布消息
function publishMessage(topic, message) {
    console.log(`发布消息到主题 [${topic}]:`, message);
    
    if (!mqttClient || !mqttClient.connected) {
        console.error('MQTT客户端未连接');
        alert('请先连接到MQTT服务器');
        return;
    }
    
    try {
        mqttClient.publish(topic, message, { qos: 0 }, (err) => {
            if (err) {
                console.error('发布消息失败:', err);
                alert(`发布失败: ${err.message}`);
            } else {
                console.log('消息发布成功');
            }
        });
    } catch (err) {
        console.error('发布消息异常:', err);
        alert(`发布异常: ${err.message}`);
    }
}

// 订阅主题
function subscribeTopic(topic) {
    console.log(`订阅主题: ${topic}`);
    
    if (!mqttClient || !mqttClient.connected) {
        console.error('MQTT客户端未连接');
        alert('请先连接到MQTT服务器');
        return;
    }
    
    try {
        mqttClient.subscribe(topic, { qos: 0 }, (err) => {
            if (err) {
                console.error('订阅失败:', err);
                alert(`订阅失败: ${err.message}`);
            } else {
                console.log('订阅成功');
                // 保存订阅主题到当前连接
                if (currentConnection) {
                    currentConnection.subscribeTopic = topic;
                }
            }
        });
    } catch (err) {
        console.error('订阅异常:', err);
        alert(`订阅异常: ${err.message}`);
    }
}

// 显示接收到的消息
function displayMessage(topic, message) {
    console.log(`显示消息 [${topic}]:`, message);
    
    const messageList = document.getElementById('message-list');
    if (messageList) {
        const messageElement = document.createElement('div');
        messageElement.className = 'message-item';
        messageElement.innerHTML = `
            <p><strong>主题:</strong> ${topic}</p>
            <p><strong>内容:</strong> ${message}</p>
            <hr>
        `;
        messageList.appendChild(messageElement);
    }
}